<template>
  <div class="pdf-all-container">
    <el-empty v-if="loadError" description="没有数据!" />

    <div class="pdf_Box" v-else>
      <div class="tool_box">
        <el-button size="mini" @click="downloadPDF"> 下载</el-button>
      </div>
      <div class="pdf_body">
        <pdf v-for="i in numLoadPages" :src="src" :page="i" :key="i" />
      </div>
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'; //引入下载的vue-pdf
import FileSave from 'file-saver';
export default {
  components: {
    pdf,
  },
  props: {
    src: {
      type: String,
      default: '/to/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf',
    },
  },
  data() {
    return {
      numLoadPages: 0, //总页数
      loadError: true, //加载成功或则失败状态
    };
  },
  watch: {
    src: {
      immediate: true,
      deep: true,
      handler(val) {
        if (!val) {
          return;
        } else {
          //  获取总页数循环
          const data = pdf.createLoadingTask(val);

          data.promise
            .then((pdf) => {
              this.numLoadPages = pdf.numPages;

              this.loadError = false;
            })
            .catch((err) => {
              console.error('pdf加载失败');
            });
        }
      },
    },
  },

  methods: {
    downloadPDF() {
      let filename = '测试.pdf';
      let url = this.src;
      //异步申请文件流
      this.$Axios
        .get(url, {
          headers: {
            'Content-Type': 'application/octet-stream',
          },
          responseType: 'blob',
        })
        .then((res) => {
          let file = new Blob([res.data], {
            type: 'application/pdf;charset=utf-8',
          });
          //直接下载而不预览
          FileSave.saveAs(file, filename);
        });
    },
  },
};
</script>

<style scoped lang="less">
.pdf-all-container {
  width: 100%;
  height: 100%;

  .el-empty {
    height: 100%;
  }

  .pdf_Box {
    height: 100%;
    .tool_box {
      padding: 0px 10px;
      box-sizing: border-box;
      height: 30px;
      display: flex;
      align-items: center;
      flex-direction: row-reverse;
    }
    .pdf_body {
      height: calc(100% - 30px);
      overflow-y: scroll;
    }
  }
}
</style>
